package com.zyp.nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhangyanping
 */
public class NIOServer {

    private  ServerSocketChannel channel;
    private  Selector selector;

    public NIOServer(int port) {
        try {
            selector = Selector.open();
            channel = ServerSocketChannel.open();
            InetSocketAddress address = new InetSocketAddress(port);

            channel.socket().bind(address);
            channel.configureBlocking(false);
            SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
            //自定义的accept处理器
            key.attach(new AcceptHandler(channel,selector));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void start() {
        try {
            while (!Thread.interrupted()) {
                System.out.println("服务端等待加入连接。。。。。。。");
                if (selector.select() == 0) {
                    continue;
                }
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey i = iterator.next();
                    //自定义行为类
                    NIOHandler handler = (NIOHandler)i.attachment();
                    handler.handle();
                    iterator.remove();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        NIOServer server = new NIOServer(9001);
        server.start();
    }
}
